package dpss.server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import dpss.commons.CustomLogger;

/**
 * The thread to listen to any UDP requests
 * 
 * @author musab.mirza
 * 
 */
class UDPListenerThread extends Thread {

	private static CustomLogger logger = CustomLogger.getInstance();

	private final AccountDatabase accountDatabase;
	private final Integer port;
	private DatagramSocket socket;
	byte[] receiveData = new byte[1024];
	byte[] sendData = new byte[1024];

	/**
	 * Initialize the thread with the passed db
	 * 
	 * @param db
	 * @throws SocketException
	 */
	public UDPListenerThread(AccountDatabase db, Integer port)
			throws SocketException {
		super();
		this.accountDatabase = db;
		this.port = port;
		socket = new DatagramSocket(port);
	}

	/**
	 * The thread starter method
	 */
	public void run() {

		logger.log("Started UDP listener on port: " + port);

		// Listening now...
		for (;;) {

			DatagramPacket receivedPacket = new DatagramPacket(receiveData, receiveData.length);

			try {
				
				socket.receive(receivedPacket);
				String receivedStr =  new String(receivedPacket.getData()).trim();
				
				switch (receivedStr){
				
					// getPlayersStatus requested
					case "getplayersinfo" :
						
						logger.log("Get players status request received via UDP from: " + receivedPacket.getAddress().toString());
						
						sendData = accountDatabase.getPlayersInfo().getBytes();
						DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivedPacket.getAddress(), receivedPacket.getPort());
						socket.send(sendPacket);
						
						logger.log("Players status info returned");
						break;
						
					default:
						logger.log("ERROR - Invalid packet recieved: " + receivedStr);
						break;
				}
				
			} catch (IOException e) {
				logger.log("ERROR - Could not receive packet");
				e.printStackTrace();
			}

		}

	}
}
